package com.zipking.cloud.springbootmybatis.util;

import com.google.common.collect.Lists;
import com.zipking.cloud.springbootmybatis.model.MyEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service
public class AsyncBatchProcessorService {

    @Async
    public <T, R> List<R> processInBatch(List<T> items, int batchSize, BatchProcessor<T, R> processor) {
        if (items == null || items.isEmpty()) {
            return Lists.newArrayList();
        }

        // 分批处理
        List<List<T>> batches = splitList(items, batchSize);
        return batches.stream()
                .parallel() // 可选：使用parallelStream来并行处理
                .map(batch -> processor.processBatch(batch))
                .flatMap(List::stream)
                .collect(Collectors.toList());
    }

    private <T> List<List<T>> splitList(List<T> list, int chunkSize) {
        return IntStream.range(0, (list.size() + chunkSize - 1) / chunkSize)
                .mapToObj(i -> list.subList(i * chunkSize, Math.min((i + 1) * chunkSize, list.size())))
                .collect(Collectors.toList());
    }

    // 定义一个处理器接口
    @FunctionalInterface
    public interface BatchProcessor<T, R> {
        List<R> processBatch(List<T> batch);
    }


}